package com.example.sqldemo

import SQLite3.Database
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.*
import com.kongzue.dialog.v3.WaitDialog
import java.io.File
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity() {

    var database:Database? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        findViewById<Button>(R.id.btn_make).setOnClickListener {
            WaitDialog.show(this,"正在处理...")

            runProgram()

        }



    }

    private fun runProgram() {
        thread(start=true){
            //1.复制assets的zip包到cache目录
            //2.解压zhukao.zip到file下
            //3.运行解密程序
            //4.加载解密后的数据库
            //5.读取文件生成表格

            AssetFileUtils.copyAssetFile(this,"zhukao.zip",PathUtils.getInternalAppCachePath(),"zhukao.zip")

            ZipUtils.unzipFile(PathUtils.getInternalAppCachePath()+"/zhukao.zip",PathUtils.getInternalAppFilesPath())

            decode()

            val dirFile = File(PathUtils.getInternalAppFilesPath()+"/output")

            if (dirFile.exists()){
                dirFile.list()?.forEach {tiku->
                    val path = PathUtils.getInternalAppFilesPath()+"/output/"+tiku
                    File(path).list()?.forEach {
                        if (it.endsWith(".db")){
                            LogUtils.d("huanghai",this,"MainActivity.runProgram","打开db",it)
                            val slist= arrayListOf<String>()

                            val query = """
                                SELECT
                                a.queId,
                                e.cateId AS id,
                                e.cateName AS name,
                                d.cateName AS cate_name,
                                c.cateName,
                                a.cateListId,
                                b.publicQueText as '公共题干',
                                a.queText as '题干',
                                a.answer,
                                replace(a.answer,' ','') as '答案',
                                g.opt as '选项',
                                a.prompt as '解析',
                                a.answerCount,
                                f.queTypeId,
                                f.queTypeName as '题类型',
                                f.memo
                                FROM
                                tQue a
                                LEFT JOIN ( SELECT queId, GROUP_CONCAT( optName || ':' || optText, '||' ) AS opt FROM tQueOpt GROUP BY queId ) g ON a.queId = g.queId
                                LEFT JOIN tCateList b ON a.cateListId = b.cateListId
                                LEFT JOIN tQueType f ON f.queTypeId = b.queTypeId
                                LEFT JOIN tCate c ON b.cateId = c.cateId
                                LEFT JOIN tCate d ON c.faId = d.cateId
                                LEFT JOIN tCate e ON d.faId = e.cateId
                            """.trimIndent()

                            LogUtils.d("huanghai",this,"MainActivity.runProgram","query",query)


                             val db = DBManager.getInstance(this,path,it)

                            slist.add("queId,id,name,cate_name,cateListId,commonBody,body,answer,opt,exp,answerCount,queTypeId,type,memo")

                            val cursor = db.rawQuery(query,null)
                            while(cursor.moveToNext()){
                                LogUtils.d("huanghai",this,"MainActivity.runProgram",cursor.getString(cursor.getColumnIndex("name")))
                                val queId = cursor.getString(cursor.getColumnIndex("queId")).emptyWithDefault("无")
                                val id = cursor.getString(cursor.getColumnIndex("id")).emptyWithDefault("无")
                                val name = cursor.getString(cursor.getColumnIndex("name")).emptyWithDefault("无")
                                val cate_name = cursor.getString(cursor.getColumnIndex("cate_name")).emptyWithDefault("无")
                                val cateListId = cursor.getString(cursor.getColumnIndex("cateListId")).emptyWithDefault("无")
                                val commonBody = cursor.getString(cursor.getColumnIndex("公共题干")).emptyWithDefault("无")
                                val body = cursor.getString(cursor.getColumnIndex("题干")).emptyWithDefault("无")
//                                val answer = cursor.getString(cursor.getColumnIndex("answer"))
                                val answer = cursor.getString(cursor.getColumnIndex("答案")).emptyWithDefault("无")
                                val opt = cursor.getString(cursor.getColumnIndex("选项")).emptyWithDefault("无")
                                val exp = cursor.getString(cursor.getColumnIndex("解析")).emptyWithDefault("无")
                                val answerCount = cursor.getString(cursor.getColumnIndex("answerCount")).emptyWithDefault("无")
                                val queTypeId = cursor.getString(cursor.getColumnIndex("queTypeId")).emptyWithDefault("无")
                                val type = cursor.getString(cursor.getColumnIndex("题类型")).emptyWithDefault("无")
                                val memo = cursor.getString(cursor.getColumnIndex("memo")).emptyWithDefault("无")
                                LogUtils.d("huanghai",this,"MainActivity.runProgram",queId,id,name,cate_name)
                                slist.add("$queId,$id,$name,$cate_name,$cateListId,\"$commonBody\",\"$body\",$answer,$opt,\"$exp\",$answerCount,$queTypeId,$type,\"$memo\"")
                            }

                            CSVUtil.exportCsv(PathUtils.getInternalAppFilesPath()+"/$tiku.csv",slist)

                        }
                    }


                }
            }

            WaitDialog.dismiss()
            ToastUtils.showShort("处理完成")
        }
    }

    fun String?.emptyWithDefault(default:String):String{
        if (this==null||this.isEmpty()){
            return default
        }
        return this.replace(",","，").replace("\r\n","&&").replace("\n","&&").replace("\r","&&").replace("""
        ""","&&")
    }

    fun decode(){
        //遍历files/zhukao文件夹
        val dir = PathUtils.getInternalAppFilesPath()+"/zhukao"
        LogUtils.d("huanghai","MainActivity.onCreate","dir",dir)
        val file = File(dir)
        LogUtils.d("huanghai","MainActivity.onCreate","exist",file.exists())
        val size = file.list()?.size?:0
        file.list()?.forEachIndexed {i,s->
            if (!s.contains(".")){
                val dbpath = "$dir/$s/MedicalDB.db"
                if (File(dbpath).exists()){
                    LogUtils.d("huanghai","MainActivity.onCreate","正在处理${i*100/size}%",s)
                    //拷贝文件
                    val destPath = PathUtils.getInternalAppFilesPath()+"/output/MedicalDB.db"
                    val destPath2 = PathUtils.getInternalAppFilesPath()+"/output/${s}/MedicalDB.db"
                    val imgPathDir = "$dir/$s/images"
                    val destPathImg = PathUtils.getInternalAppFilesPath()+"/output/${s}/images"
                    FileUtils.copyFile(dbpath,destPath)
                    database = getDatabaseByName(destPath)
                    database?.rekey("")
                    FileUtils.copyFile(destPath,destPath2)
                    FileUtils.delete(destPath)
                    FileUtils.copyDir(imgPathDir,destPathImg)
                }
            }

        }

    }




    fun key(str: String) {
        val b = ByteArray(str.length)
        for (i in str.indices) {
            val c = str.toCharArray()[i]
            b[i] = ((c.toInt()).and(0xff)).xor(((c.toInt()).shr(0x8))).toByte()
        }

        println(b.toString())
        val s = String(b)
        println(s)
        println(byteArrayToHexStr(b))
    }


    fun byteArrayToHexStr(byteArray: ByteArray?): String? {
        if (byteArray == null) {
            return null
        }
        val hexArray = "0123456789ABCDEF".toCharArray()
        val hexChars = CharArray(byteArray.size * 2)
        for (j in byteArray.indices) {
            val v = (byteArray[j]).toInt()
            hexChars[j * 2] = hexArray[v ushr 4]
            hexChars[j * 2 + 1] = hexArray[v and 0x0F]
        }
        return String(hexChars)
    }


    fun getDatabaseByName(dbpath: String): Database? {
        val file = File(dbpath)
        val database = Database()
        return if (!file.exists()) {
            database
        } else try {
            LogUtils.d("huanghai","MainActivity.getDatabaseByName","file.absolutePath",file.absolutePath)
            database.open(file.absolutePath, 0x6)
            database.key(DBCipherHelper.DB_PWD)
            database
        } catch (e: Exception) {
            e.printStackTrace()
            database
        }
    }

}

